// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// f [author] rhyme_lph
// C [email]  rhymelph@gmail.com
// g [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/invite_member_entity.dart';
import 'package:finance_app/src/entities/invite_member_model.dart';
import 'package:finance_app/src/entities/role_permission_entity.dart';
import 'package:finance_app/src/provider/invite_team/invite_team_members_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/button/assistant_button.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/down_button_form.dart';
import 'package:finance_app/src/widgets/input/input_field.dart';
import 'package:finance_app/src/widgets/input/phone_number_input_field.dart';
import 'package:finance_app/src/widgets/input/user_name_down_pop_input_field.dart';
import 'package:finance_app/src/widgets/pop/normal_pop.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';

@RouterMeta(paramName: "inviteTeamMembersPage")
class InviteTeamMembersPage extends StatefulWidget {
  final bool isSelectManually;
  final bool isSelectPhoneBook;
  final bool isSelectEmployee;

  const InviteTeamMembersPage({Key key, this.isSelectManually, this.isSelectPhoneBook, this.isSelectEmployee}) : super(key: key);

  @override
  _InviteTeamMembersPageState createState() => _InviteTeamMembersPageState();
}

class _InviteTeamMembersPageState extends State<InviteTeamMembersPage> with PagePresenter<InviteTeamMembersPage, InviteTeamMembersProvider> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (widget.isSelectManually == true) {
        provider.onAddManually();
      } else if (widget.isSelectPhoneBook == true) {
        provider.onImportFromPhoneBook();
      } else if (widget.isSelectEmployee == true) {
        provider.onAddFromEmployee();
      }
    });
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.manage_users,
        actions: [
          AssistantButton(
            paddingRight: 0.0,
            entryPoint: "Invite Team Members",
          ),
          NormalMorePopupButton(
            horizontalPadding: getDp(10),
            onSelect: provider.onSelectMenu,
            menuList: provider.menuList,
          ),
        ],
      );

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            AppSpaces.h25,
            _buildUserNameInfo(),
            AppSpaces.h25,
            PressedOpacityButton(
              padding: EdgeInsets.symmetric(horizontal: getDp(35)),
              onPressed: provider.onNavManageRolePage,
              child: Text(
                S.current.manage_role_access,
                style: TextStyle(
                  color: aceBlueColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 20 / 18,
                ),
              ),
            ),
            AppSpaces.h25,
            AppSpaces.grayH6,
            Padding(
              padding: EdgeInsets.only(left: getDp(35), top: getDp(20), right: getDp(35)),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        S.current.team_members,
                        style: TextStyle(
                          color: aceBlackColor,
                          fontSize: getSp(18),
                          fontWeight: FontWeight.w700,
                          height: 20 / 18,
                        ),
                      ),
                      listBuilder<String>(
                        selector: (_, __) => __.currentSelectEnable,
                        builder: (BuildContext context, String value, Widget child) => DownButtonForm(
                          title: LanguageUtils.translateStatus(value),
                          onTap: provider.onChangeSelectEnable,
                        ),
                      ),
                    ],
                  ),
                  super.buildEmptyWidget,
                  AppSpaces.h20,
                ],
              ),
            ),
            AppSpaces.grayH6,
            Padding(
              padding: EdgeInsets.only(left: getDp(35), top: getDp(20)),
              child: Text(
                S.current.invite_members,
                style: TextStyle(
                  color: aceBlackColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 20 / 18,
                ),
              ),
            ),
            AppSpaces.h20,
            listBuilder<int>(
              selector: (_, __) => __.modelList.length,
              builder: (BuildContext context, int value, Widget child) => Column(
                children: List.generate(value, (index) => _buildInviteMember(index)),
              ),
            ),
            listBuilder<bool>(
              selector: (_, __) => __.modelList.length > 0,
              builder: (BuildContext context, bool value, Widget child) => Visibility(
                child: AppSpaces.h20,
                visible: value,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: getDp(35), right: getDp(30)),
              child: Column(
                children: [
                  AddButton(
                    title: S.current.add_from_employee_list,
                    onTap: provider.onAddFromEmployee,
                  ),
                  AppSpaces.h15,
                  AddButton(
                    title: S.current.import_from_phone_book,
                    onTap: provider.onImportFromPhoneBook,
                  ),
                  AppSpaces.h15,
                  AddButton(
                    title: S.current.add_manually,
                    onTap: provider.onAddManually,
                  ),
                ],
              ),
            ),
            AppSpaces.h40,
            listBuilder<bool>(
                selector: (_, __) => __.modelList.length > 0,
                builder: (BuildContext context, bool value, Widget child) => Visibility(
                      child: child,
                      visible: value,
                    ),
                child: NormalButton(
                  title: S.current.invite,
                  onTap: provider.onInvite,
                )),
            AppSpaces.h20,
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            AppSpaces.h25,
            _buildUserNameInfo(),
            AppSpaces.h25,
            PressedOpacityButton(
              padding: EdgeInsets.symmetric(horizontal: getDp(35)),
              onPressed: provider.onNavManageRolePage,
              child: Text(
                S.current.manage_role_access,
                style: TextStyle(
                  color: aceBlueColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 20 / 18,
                ),
              ),
            ),
            AppSpaces.h25,
            AppSpaces.grayH6,
            Padding(
              padding: EdgeInsets.only(left: getDp(35), top: getDp(20), right: getDp(35)),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        S.current.team_members,
                        style: TextStyle(
                          color: aceBlackColor,
                          fontSize: getSp(18),
                          fontWeight: FontWeight.w700,
                          height: 20 / 18,
                        ),
                      ),
                      listBuilder<String>(
                        selector: (_, __) => __.currentSelectEnable,
                        builder: (BuildContext context, String value, Widget child) => DownButtonForm(
                          title: LanguageUtils.translateStatus(value),
                          onTap: provider.onChangeSelectEnable,
                        ),
                      ),
                    ],
                  ),
                  listBuilder<List<InviteMemberEntity>>(
                    selector: (_, __) => __.data,
                    builder: (BuildContext context, List<InviteMemberEntity> value, Widget child) => value.length == 0
                        ? Container()
                        : Padding(
                            padding: EdgeInsets.only(
                              top: getDp(20),
                              bottom: getDp(20),
                            ),
                            child: Column(
                              children: List.generate(value.length, (index) {
                                final e = value[index];
                                return _buildTeamMember(
                                    index: index, name: e.name, role: e.role, avatar: e.avatar, isPending: e.isPending == 1, disable: e.enabled == 0);
                              }),
                            ),
                          ),
                  ),
                ],
              ),
            ),
            AppSpaces.grayH6,
            Padding(
              padding: EdgeInsets.only(left: getDp(35), top: getDp(20)),
              child: Text(
                S.current.invite_members,
                style: TextStyle(
                  color: aceBlackColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 20 / 18,
                ),
              ),
            ),
            AppSpaces.h20,
            Column(
              children: [
                listBuilder<int>(
                  selector: (_, __) => __.modelList.length,
                  builder: (BuildContext context, int value, Widget child) => Column(
                    children: List.generate(value, (index) => _buildInviteMember(index)),
                  ),
                ),
              ],
            ),
            listBuilder<bool>(
              selector: (_, __) => __.modelList.length > 0,
              builder: (BuildContext context, bool value, Widget child) => Visibility(
                child: AppSpaces.h20,
                visible: value,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: getDp(35), right: getDp(30)),
              child: Column(
                children: [
                  AddButton(
                    title: S.current.add_from_employee_list,
                    onTap: provider.onAddFromEmployee,
                  ),
                  AppSpaces.h15,
                  AddButton(
                    title: S.current.import_from_phone_book,
                    onTap: provider.onImportFromPhoneBook,
                  ),
                  AppSpaces.h15,
                  AddButton(
                    title: S.current.add_manually,
                    onTap: provider.onAddManually,
                  ),
                ],
              ),
            ),
            AppSpaces.h40,
            listBuilder<bool>(
                selector: (_, __) => __.modelList.length > 0,
                builder: (BuildContext context, bool value, Widget child) => Visibility(
                      child: child,
                      visible: value,
                    ),
                child: NormalButton(
                  title: S.current.invite,
                  onTap: provider.onInvite,
                )),
            AppSpaces.h20,
          ],
        ),
      );

  Widget _buildTeamMember({int index, String avatar, String name, RolePermissionEntity role, bool isPending, bool disable}) {
    return Padding(
      padding: EdgeInsets.only(bottom: getDp(12)),
      child: Row(
        children: [
          CircleAvatar(
            radius: getDp(19),
            backgroundImage: Config.toImageProvider(avatar),
          ),
          SizedBox(
            width: getDp(13),
          ),
          Expanded(
            child: Text(
              name,
              style: TextStyle(
                color: aceBlackColor,
                fontSize: getSp(18),
                fontWeight: FontWeight.w700,
                height: 22 / 18,
              ),
            ),
          ),
          if (isPending) ...[
            NormalRedTagWidget(
              content: S.current.invitation_sent,
            ),
            AppSpaces.w15,
            _buildCloseButton(onPressed: () => provider.onRemoveTeamMembers(index)),
          ] else
            listBuilder<List<RolePermissionEntity>>(
              builder: (BuildContext context, List<RolePermissionEntity> value, Widget child) => SizedBox(
                width: getDp(125),
                height: getDp(54),
                child: NormalPop<RolePermissionEntity>(
                  horizontalPadding: 0,
                  select: disable ? provider.roles.last : role,
                  group: value,
                  buildDisplayName: (e) => e.name,
                  hint: '',
                  onSelect: role.canEdit == 0 ? null : (data) => provider.onSelectInvitationMember(data, index),
                ),
              ),
              selector: (_, __) => provider.roles,
            ),
        ],
      ),
    );
  }

  //用户信息
  Widget _buildUserNameInfo() {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: getDp(35),
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: getDp(19),
            backgroundImage: Config.toImageProvider(Config.userProfile.avatar),
          ),
          SizedBox(
            width: getDp(20),
          ),
          Expanded(
            child: Text(
              '${Config.userProfile.name}',
              style: TextStyle(
                color: aceBlackColor,
                fontSize: getSp(18),
                fontWeight: FontWeight.w700,
                height: 22 / 18,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 邀请好友输入界面
  Widget _buildInviteMember(int index) {
    return listBuilder<InviteMemberModel>(
      selector: (_, __) => __.modelList[index],
      builder: (BuildContext context, InviteMemberModel inviteValue, Widget child) => Container(
        padding: EdgeInsets.only(
          bottom: getDp(15),
        ),
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.only(left: getDp(35), right: getDp(30)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    S.current.member_(index + 1),
                    style: TextStyle(
                      color: aceDarkGrayColor,
                      fontSize: getSp(16),
                      fontWeight: FontWeight.w400,
                      height: 22 / 16,
                    ),
                  ),
                  _buildCloseButton(onPressed: () => provider.onRemoveInviteMembers(index)),
                ],
              ),
            ),
            AppSpaces.h15,
            UserNameDownPopInputField(
              horizontalPadding: getDp(35),
              controller: inviteValue.nameController,
              focusNode: inviteValue.nameFocusNode,
              defaultRole: inviteValue.role,
              roles: []
                ..addAll(provider.roles)
                ..removeLast(),
              roleCallback: (data) => provider.onUpdateType(data, index),
            ),
            Container(
              margin: EdgeInsets.only(
                top: getDp(10),
                bottom: getDp(10),
                left: getDp(30),
              ),
              child: Row(
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Radio(
                        value: 0,
                        groupValue: inviteValue.radioSelect,
                        onChanged: (value) => provider.onRaidoChoice(index,value),
                      ),
                      Text(
                        S.current.email,
                        style: TextStyle(
                          color: aceDarkGrayColor,
                          fontSize: getSp(16),
                          fontWeight: inviteValue.radioSelect == 0 ? FontWeight.bold : FontWeight.w400,
                          height: 22 / 16,
                        ),
                      )
                    ],
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Radio(
                        value: 1,
                        groupValue: inviteValue.radioSelect,
                        onChanged: (value) => provider.onRaidoChoice(index,value),
                      ),
                      Text(
                        S.current.mobile_number,
                        style: TextStyle(
                          color: aceDarkGrayColor,
                          fontSize: getSp(16),
                          fontWeight: inviteValue.radioSelect == 1 ? FontWeight.bold : FontWeight.w400,
                          height: 22 / 16,
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => inviteValue.countryCode,
              builder: (BuildContext context, String value, Widget child) => inviteValue.radioSelect == 0
                  ? InputField(hint: S.current.email, focusNode: inviteValue.emailFocusNode, controller: inviteValue.emailController)
                  : PhoneNumberInputField(
                      horizontalPadding: getDp(35),
                      controller: inviteValue.phoneController,
                      focusNode: inviteValue.phoneFocusNode,
                      defaultCountryCode: value,
                      countryCodeCallback: (data) => provider.onUpdateCountryCode(data, index),
                    ),
            )
          ],
        ),
      ),
    );
  }

  PressedOpacityButton _buildCloseButton({VoidCallback onPressed}) {
    return PressedOpacityButton(
      onPressed: onPressed,
      padding: EdgeInsets.symmetric(
        horizontal: getDp(8),
        vertical: getDp(5),
      ),
      child: SvgPicture.asset(
        A.assetsImagesStyleDelete_1_1,
        width: getDp(12),
        height: getDp(12),
      ),
    );
  }
}
